package com.wrl.mmall.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Wang Renlei
 * @Date 2019/10/15 0015
 */
@Slf4j
public class CookieUtil {

    //写在一级域名下，则二级域名可以读到
    private static final String COOKIE_DOMAIN = PropertiesUtil.getProperty("cookie.domain");
    //cookie的名字。服务端传给客户端的名字
    private static final String COOKIE_NAME = PropertiesUtil.getProperty("cookie.name");

    //写入cookie
    public static void writeLoginToken(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie(COOKIE_NAME, token);
        cookie.setDomain(COOKIE_DOMAIN);
        cookie.setPath("/");    //代表下一级的目录
        cookie.setHttpOnly(true);   //不允许使用脚本访问cookie，防止脚本攻击

        //单位是秒。如果不设置，就不会写入硬盘，而是写在内存，只在当前页面中
        cookie.setMaxAge(60 * 60 * 24 * 365);   //一年
        log.info("write cookieName:{},cookieValue:{}", cookie.getName(), cookie.getValue());
        response.addCookie(cookie);
    }

    //读取cookie
    public static String readLoginToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
//                log.info("read cookieName:{},cookieValue:{}", cookie.getName(), cookie.getValue());
                if(StringUtils.equals(cookie.getName(), COOKIE_NAME)){
//                    log.info("return cookieName:{},cookieValue:{}", cookie.getName(), cookie.getValue());
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    //销毁cookie
    public static void delLoginToken(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie ck : cookies) {
                if(StringUtils.equals(ck.getName(), COOKIE_NAME)){
                    ck.setDomain(COOKIE_DOMAIN);
                    ck.setPath("/");
                    //代表删除此cookie
                    ck.setMaxAge(0);
                    log.info("del cookieName:{},cookieValue:{}", ck.getName(), ck.getValue());
                    response.addCookie(ck);
                    return;
                }
            }
        }
    }

}
